<template>
    <div class="w-full overflow-auto">
        <div class="px-6 py-4 bg-white rounded-[6px] mb-6">
            <div class="text-default text-[18px] font-[400] flex items-center mb-1 leading-6">
                <span class="text-custom-text text-[18px] font-[400]">{{ paperData.name }}</span>
                <img class="pl-2" src="@/assets/images/star.png" alt="" v-for="item in paperData.level">
            </div>
            <div class="flex items-center">
                <div class="flex items-center mr-6 leading-[22px]">
                    <span class="text-[#000]/45 text-[14px] font-[400]" @click="setPaperSubmit">考核名称：</span>
                    <span class="text-[#000]/65 text-[14px] font-[400]">{{ paperData.name }}</span>
                </div>
                <div class="flex items-center mr-6 leading-[22px]">
                    <span class="text-[#000]/45 text-[14px] font-[400]">总分：</span>
                    <span class="text-[#000]/65 text-[14px] font-[400]">{{ paperData.total_score }}</span>
                </div>
                <div class="flex items-center mr-6 leading-[22px]">
                    <span class="text-[#000]/45 text-[14px] font-[400]">建议时长：</span>
                    <span class="text-[#000]/65 text-[14px] font-[400]">{{ paperData.duration }}分钟</span>
                </div>
                <div class="flex items-center leading-[22px]">
                    <span class="text-[#000]/45 text-[14px] font-[400]">上次考核：</span>
                    <span class="text-[#000]/65 text-[14px] font-[400]">{{ paperData.last_exam_time || '-' }}</span>
                </div>
            </div>
        </div>
        <div>
            <div ref="container" class="exe-container">
                <iframe style="width: 100%; height: 100%;" v-if="paperData.c_id" id="unityFrame" 
                    :src="paperData.c_id + '?width=' + containerWidth + '&height=' + containerHeight + '&t=' + timestamp"
                    allowfullscreen="true" title="Iframe Example"></iframe>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { examApi } from "@/api/index.js";
import { StorageUtil } from "@/utils/common.js";
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { useRoute, useRouter } from "vue-router";
import dayjs from 'dayjs';

const route = useRoute();
const router = useRouter();
const questionData = ref([]);
const testId = ref('');
const container = ref(null);
const containerWidth = ref(1000);
const containerHeight = ref(600);

const paperData = ref({});
const timestamp = ref(Date.now());

const listenerMessage = (event) => {
    console.log(event);
    
    const data = JSON.parse(event.data)
    //开始实训
    if (data.Name == 'NotifyBeginTraining') {
        const { paperId, chapterId } = route.query;
        setPaperStart()
        SendMessageToUnity(JSON.stringify({
            "Name": "ClientEnter",
            "Parameters": {
                "paper_id": paperId,
                "chapter_id": chapterId
            }
        }))
    } 
    //实训结束
    if (data.Name === "NotifyEndTraining") {
        SendMessageToUnity(JSON.stringify({"Name": "ClientQuit"}))
    }
    //实训完成
    if (data.Name === "SendTrainingResult") {
        setPaperSubmit(data.Parameters)
    }
}
const SendMessageToUnity = (message) => {
    var unityWindow = document.getElementById("unityFrame", "*").contentWindow;
    unityWindow.postMessage(message, "*");
}

onMounted(() => {
    paperData.value = StorageUtil.session.get('paperData');
    // getQuestionList();
    if (!paperData.value.c_id) {
        ElMessage.info('暂无实训资源！');
    }
    window.addEventListener("message", listenerMessage);
    
    // 设置初始宽高
    if (container.value) {
        containerWidth.value = container.value.clientWidth - 50 || 1000;
        containerHeight.value = container.value.clientHeight - 50 || 600;
    }
});

onUnmounted(() => {
    paperData.value.c_id = null
    window.removeEventListener('message', listenerMessage);
});

const setPaperStart = () => {
    const { paperId, chapterId, test_id } = route.query;
    const params = {
        paper: paperId,
        chapter: chapterId
    };
    if (test_id) {
        params['test_id'] = test_id
    }
    examApi.setPaperStart(params).then(res => {
        testId.value = res;
    });
};

// 获取试题
const getQuestionList = () => {
    const { paperId, chapterId } = route.query;
    examApi.getQuestionList(paperId, chapterId).then(res => {
        questionData.value = res;
        setPaperStart()
    });
};

// 提交考核
const setPaperSubmit = (data) => {
    const { paperId, chapterId } = route.query;
    const params = {
        paper: paperId,
        chapter: chapterId,
        test_id: testId.value,
        ...data
    };
    params['start_time'] = dayjs(params.start_time).format('YYYY-MM-DD HH:mm:ss')
    params['finish_time'] = dayjs(params.finish_time).format('YYYY-MM-DD HH:mm:ss')
    examApi.setPaperSubmit(params).then(res => {
        //提交结果. -1: 考核失败；1: 全部完成； 0: 下一关
        StorageUtil.session.set('assessResultData', res);
        const path = res.status == -1 ? '/examCourses/failfullLevel' : res.status == 1 ? '/examCourses/assesseEnd' : '/examCourses/successfulLevel';
        router.push({
            path,
            query: {
                paperId,
                chapterId,
                testId: testId.value
            }
        });
    });
};

// 添加刷新iframe的方法
const refreshIframe = () => {
    timestamp.value = Date.now();
};

// 在需要重新加载iframe时调用refreshIframe方法
// 例如可以在某些事件处理函数中调用
</script>
<style scoped>
.control-panel {
    display: flex;
    align-items: center;
    padding: 10px 20px;
    gap: 10px;
    background-color: rgba(255, 255, 255, 0.8);
    padding: 5px 10px;
    border-radius: 4px;
}

.alt-tip {
    color: #666;
    font-size: 14px;
}

.exe-container {
    width: 100%;
    height: 800px;
    transition: all 0.3s;
}
</style>